<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  title: ''
})
// ----
const displays = [{
  value: '1',
  text: '左右滑动'
}, {
  value: '2',
  text: '上下滑动'
}]
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// ----
const getCurrencyInfo = (callback) => {
  // --获取定制功能--
  const customItems = forSys.filter((item) => { return String(item.name) === 'market_customFuncUser' })
  if (Number(customItems.length) === 1) {
    proxy.$Myfun.getJsonData(customItems[0].value, (resJson) => {
      if (Number(resJson.length) > 0) {
        // --forAlbum--
        if (resJson[0].album && Number(resJson[0].album.length) > 0) {
          resJson[0].album.some((item) => {
            if (String(item.telphone) === String(logUser.telphone)) user.title = item.name
          })
        }
      }
    })
  }
  // --设置网页title--
  const forTitle = user.title + document.title
  setAppTitle(forTitle)
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'album-category/index',
    forData: {
      params: {
        'AlbumCategorySearch[dealer_id]': logUser.id,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forDesc = ''
    let forImage = ''
    let forImgs = []
    let forAlbums = []
    let forDisplayText = ''
    await proxy.$Myfun.getJsonData(item.remark, (resJson) => {
      const RJData = resJson[0] || {}
      forDesc = proxy.$Myfun.setText(RJData.description)
      if (RJData.share_img && Number(RJData.share_img.length) > 0) {
        forImage = RJData.share_img[0].image
        forImgs = RJData.share_img
      }
      if (RJData.albums && Number(RJData.albums.length) > 0) forAlbums = RJData.albums
      // ----
      displays.some((current) => {
        if (String(current.value) === String(RJData.display_id)) forDisplayText = current.text
      })
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      desc: forDesc,
      image: forImage,
      imgs: forImgs,
      albums: forAlbums,
      displayText: forDisplayText
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const forItem = item || {}
      proxy.$Myfun.openPage(proxy, 'push', 'AlbumAdm', { id: forItem.id })
      break
    }
    case 2: {
      proxy.$Myfun.openPage(proxy, 'push', 'AlbumShare', { id: item.id, dealer_id: logUser.id })
      break
    }
    case 3: {
      const options = {
        content: proxy.$Global.layer.conDel,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnDel,
          class: 'xw-color-24',
          callback: async () => {
            layerBox.value.close()
            // ----
            proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
            // ----
            const opts = {
              region: proxy.$Global.aoss.region,
              bucket: proxy.$Global.aoss.bucket,
              accessKeyId: proxy.$Global.aoss.accessKeyId,
              accessKeySecret: proxy.$Global.aoss.accessKeySecret
            }
            if (Number(item.imgs.length) > 0) {
              const imgArr = item.imgs
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            if (Number(item.albums.length) > 0) {
              const imgArr = item.albums
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            // ----
            await proxy.$http.delete('album-category/delete?id=' + item.id, {
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            proxy.$Myfun.disLoading(layerLoading.value, 'close')
            mescroll.scrollTo(0)
            mescroll.resetUpScroll()
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
    case 4: {
      proxy.$Myfun.openPage(proxy, 'push', 'AlbumCustomer', { id: item.id })
      break
    }
    case 5: {
      proxy.$Myfun.openPage(proxy, 'push', 'AlbumQrCode', { id: item.id })
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => {
  if (mescroll) mescroll.destroy()
  proxy.$Store.remove('albums')
})
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-title xw-act xw-flex-W1">营销图册列表</div>
        <span class="TOP-submit xw-WBlue xw-radius-3" @click="getAuditFun(1)">创建营销图册</span>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-album xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items">
            <div class="LAM-con xw-act xw-flex xw-flex-align" @click="getAuditFun(2, item)">
              <div class="LAM-avar xw-radius-3" v-if="item.image"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></div>
              <div class="LAM-info xw-flex-W1">
                <div class="LAM-title xw-ellipsis">{{item.name}}</div>
                <div class="LAM-desc xw-ellipsis" v-if="item.desc">{{item.desc}}</div>
              </div>
            </div>
            <div class="LAM-btns xw-flex xw-flex-align xw-flex-justify">
              <div class="xw-btn xw-WBlue" @click="getAuditFun(1, item)">修改</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(3, item)">删除</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(4, item)">客服</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(5, item)">二维码</div>
              <div class="xw-color-13" v-if="item.displayText">{{item.displayText}}</div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-album li { position: relative; margin: 1rem 1rem 0; padding: 1rem 1rem 0; overflow: hidden; }
.list-album li:nth-of-type(1) { margin-top: 0; }
.LAM-avar { margin-right: 1rem; width: 6rem; height: 6rem; }
.LAM-title { line-height: 3rem; font-size: 1.7rem; font-weight: bold; }
.LAM-desc { line-height: 3rem; }
.LAM-btns { padding: 1rem 0; }
</style>
